<template>
  <el-drawer :visible.sync="visible" direction="rtl" size="70%" :wrapper-closable="false">
    <template #title>
      <div style="display:flex;justify-content: space-between;align-items: center;padding-right:20px;">
        <span>
          {{ type === 'export' ? '查看JSON' : '导入JSON' }}
        </span>
        <el-button v-if="type === 'export'" class="copyBtn" type="primary">复制JSON</el-button>
        <el-button v-if="type === 'import'" type="primary" @click="update">更新</el-button>
      </div>
    </template>
    <textarea id="copyContent" ref="textarea" :value="formConfig" />
  </el-drawer>
</template>
<script>
import { isObject } from '@/utils/tools'
import Clipboard from 'clipboard'
export default {
  name: 'PreviewJson',
  props: {
    config: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      visible: false,
      direction: 'rtl',
      json: '',
      // export OR import
      type: 'export'
    }
  },
  computed: {
    formConfig () {
      return this.type === 'export' ? JSON.stringify(this.config, null, '\t') : ''
    }
  },
  mounted () {
    this.bindCopy()
  },
  methods: {
    show (type) {
      this.type = type
      this.visible = true
    },
    hide () {
      this.visible = false
    },
    update () {
      try {
        let v = this.$refs.textarea.value
        if (!v) {
          this.$message.info('请填写正确的JSON')
          return
        }
        v = JSON.parse(v)
        if (!isObject(v.formProps)) {
          this.$message.error('请填写正确的formProps对象')
        }
        if (!Array.isArray(v.elements) || !v.elements.length) {
          this.$message.error('请填写正确的elements数组')
        }
        this.$emit('input', v)
      } catch (e) {
        this.$message.error(`JSON格式错误信息：${e.message}`)
      }
    },
    bindCopy () {
      const clipboard = new Clipboard('.copyBtn', {
        text: trigger => {
          const code = this.$refs.textarea.value
          this.$notify({
            title: '成功',
            type: 'success',
            position: 'bottom-right',
            message: '代码已复制到剪切板，可粘贴。'
          })
          return code
        }
      })
      clipboard.on('error', () => {
        this.$message.error('代码复制失败，请手动复制')
      })
    }
  }
}
</script>
<style scoped>
  textarea {
    margin: 0;
    padding: 10px;
    display: block;
    width: 100%;
    height: 100%;
    background: #1e1e1e;
    color: #9cdcfe;
    font-family: Arial;
    font-size: 17px;
    line-height: 1.8;
    resize: none;
    outline: none;
    border: none;
  }
</style>
